<template>
	<!-- 这层div很重要，不能删，是为了解决key值渲染可能导致父级组件refs列表重排的问题 -->
	<div>
		<el-cascader
			ref="cascaderChapter"
			placeholder="请选择章节"
			clearable
			:value="cascaderValue"
			:collapse-tags="true"
			:show-all-levels="false"
			:props="props"
			:options="options"
			:key="cascaderKey"
			@change="change"
		/>
	</div>
</template>

<script>
	import cbApi from "@rc/apis/cb/index.mjs";
	export default {
		props: {
			/**
			 * 当前的默认的选中值
			 * 1.支持v-model
			 * 2.默认单选，支持传入两种风格  1.[子chapterId] 2.[父chapterId,子chapterId]，注：修改后传出的是第二种格式
			 * 3.多选(propsOptions.multiple = true)  1. [子chapterId,子chapterId,...]  2. [[父chapterId,子chapterId], [父chapterId,子chapterId]...]，注：修改后传出的是第二种格式
			 */
			value: {
				type: Array,
				default: () => []
			},
			// 科目id
			subjectId: {
				type: String,
				default: ""
			},
			// 查询几级默认2级
			chapterLevel: {
				type: String,
				default: "2"
			},
			// cascader组件的props参数，会与组件配置的进行合并 https://element.eleme.cn/#/zh-CN/component/cascader
			propsOptions: {
				type: Object,
				default: () => {}
			},
			// 是否查询禁用的章节
			showDisabledChapter: {
				type: Boolean,
				default: false
			}
		},
		model: {
			event: "change"
		},
		data() {
			return {
				options: [], // 树状列表
				flatOptions: [], // 扁平化的列表
				cascaderKey: 1,
				changeValue: null //存储当前选择的值,供api_getChapterList使用 因为value或cascaderValue无法立即得到改变的最新数据
			};
		},
		computed: {
			// 级联框基础配置
			props() {
				return {
					multiple: false,
					value: "chapterId",
					label: "chapterTitle",
					...this.propsOptions
				};
			},
			//经过处理的，符合cascader组件格式需求标准的value
			cascaderValue() {
				let result = [];
				if (this.props.multiple) {
					// 多选类型
					result = this.value.map((i) => {
						if (Array.isArray(i)) {
							// 父级子级全有的多选[[],[]]
							return i;
						} else {
							// 只有子级的多选[子id1,子id2]
							const findItem = this.flatOptions.find((i2) => i2.chapterId === i);
							return findItem ? findItem.ids : [];
						}
					});
					result = result.filter((i) => i); // 过滤掉为null的未匹配上的id
				} else {
					// 单选类型
					const childrenId = this.value[this.value.length - 1];
					const findItem = this.flatOptions.find((i) => i.chapterId === childrenId);
					result = findItem ? findItem.ids : [];
				}
				return result;
			}
		},
		watch: {
			subjectId: {
				immediate: true,
				handler(val) {
					this.cascaderKey++;
					if (!val) {
						this.options = [];
						return;
					}
					this.queryList(val);
				}
			}
		},
		methods: {
			queryList(subjectId) {
				cbApi.queryChapterTree({
					data: {
						subjectId,
						chapterLevel: this.chapterLevel,
						showUnAvl: this.showDisabledChapter ? "Y" : "N"
					},
					success: (data) => {
						this.options = data || [];
						// 扁平化的递归函数
						const flatFun = (arr, item, ids) => {
							arr.push({
								chapterId: item.chapterId,
								chapterTitle: item.chapterTitle,
								ids: [...ids, item.chapterId] // 父子id集合
							});
							if (item.children && item.children.length) {
								item.children.forEach((item2) => {
									flatFun(arr, item2, [...ids, item.chapterId]);
								});
							}
						};
						this.options.forEach((item2) => {
							flatFun(this.flatOptions, item2, []);
						});
					}
				});
			},
			change(data) {
				this.changeValue = data;
				this.$emit("change", data);
				this.$emit("change-detail", this.api_getChapterList());
			},
			/**
			 * 获取目前勾选的详细的章节信息
			 * 名称为最后一级名称
			 */
			api_getChapterList() {
				let chapterList = this.changeValue ? this.changeValue : this.cascaderValue;
				if (!chapterList.length) {
					return [];
				}
				const getLabelName = (flatOptions, chapterId) => {
					const chapter = flatOptions.find((option) => option.chapterId === chapterId);
					return chapter ? chapter.chapterTitle : "";
				};
				if (this.props.multiple) {
					//多选
					return chapterList.map((chapter) => {
						const chapterId = chapter[chapter.length - 1];
						return {
							chapterId: chapterId,
							chapterName: getLabelName(this.flatOptions, chapterId),
						};
					});
				} else {
					const chapterId = chapterList[chapterList.length - 1];
					return [
						{
							chapterId: chapterId,
							chapterName: getLabelName(this.flatOptions, chapterId),
						}
					];
				}
			},
			/**
			 * 获取目前勾选的详细的章节信息
			 * 返回的章节名称是一级-二级-。。。-最后一级拼接完整的
			 */
			api_getChapterListFullName() {
				let chapterList = this.changeValue ? this.changeValue : this.cascaderValue;
				if (!chapterList.length) {
					return [];
				}
				// ele框架在数据结构层已经提供了，没必要再谢一边了，浪费资源
				const treeToLabel = (data, arr) => {
					let result = [];
					const childrenTreeToLabel = (data, arr, result) => {
						for (let j = 0; j < data.length; j++) {
							if (arr[0] == data[j].chapterId) {
								result.push(data[j].chapterTitle);
								if (data[j].children && arr.length > 1) {
									childrenTreeToLabel(data[j].children, arr.slice(1), result);
								}
								break;
							}
						}
					};
					childrenTreeToLabel(data, arr, result);
					return result.join("-");
				};
				// ele框架在数据结构层已经提供了，没必要再谢一边了，浪费资源
				if (this.props.multiple) {
					//多选
					return chapterList.map((chapter) => {
						return {
							chapterId: chapter[chapter.length - 1],
							chapterName: treeToLabel(this.options, chapter, []),
						};
					});
				} else {
					return [
						{
							chapterId: chapterList[chapterList.length - 1],
							chapterName: treeToLabel(this.options, chapterList, []),
						}
					];
				}
			},
			api_getCheckedNodes() {
				return this.$refs.cascaderChapter.getCheckedNodes();
			}
		}
	};
</script>

<style scoped lang="less">
	/deep/ .el-cascader {
		width: 100%;
	}
	/deep/ .el-cascader__tags .el-tag {
		height: 23px;
		line-height: 23px;

		.el-icon-close {
			top: 1px;
		}
	}
</style>
